package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class LoginIo {
	
	FileReader fr=null;
	BufferedReader br=null;
	FileWriter fw=null;
	BufferedWriter bw=null;
	ArrayList<UserInfo> al=null;
	File f=new File("empUsers.txt");
	public LoginIo()
	{
		  if(!f.exists()) //保证密码文件的存在
			try{
				   f.createNewFile();
			   }catch(IOException e){
				   e.printStackTrace();
			   }

		   al=new ArrayList<UserInfo>(); //初始化集合
		   empInputUsers(); //将用户读入al集合
	}
	public int sizeUser() {//返回用户的个数
		return al.size(); 
	}
	public boolean isUser(String user,String passWd) { 
		//判断用户名和密码是否正确
		for(int i=0;i<al.size();i++)
		{
			UserInfo uinfo=al.get(i);
			if(user.equals(uinfo.getUser())&&passWd.equals(uinfo.getPassWd()))
				return true;
		}
		return false;
	}
	//文件输入  实现读取用户账号和密码
	public void empInputUsers()
	{
		String s=null;
		try {
			fr=new FileReader("empUsers.txt");
			br=new BufferedReader(fr);
			while(br.ready())
			{
				s=br.readLine();
				String[] ss=s.split("#");
				UserInfo uu=new UserInfo(ss[0], ss[1]);
				this.al.add(uu);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				br.close();
				fr.close();
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}
		//return al;
	}
	public void empOutputUsers(String user,String passWd) //将一个用户写入文件empUsers.txt
	{
		UserInfo ui=new UserInfo(user,passWd);  //新建一个用户
		try {
			fw=new FileWriter("empUsers.txt");
			bw=new BufferedWriter(fw);
			this.al.add(ui);
			for(int i=0;i<al.size();i++)
			{
				UserInfo uinfo=al.get(i);
				String ss=uinfo.getUser()+"#"+uinfo.getPassWd();
				bw.write(ss+"\r\n");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				bw.close();
				fw.close();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}

}
